<script setup lang="ts">
  import { GenTableField, GenTableFieldForDB, GenTableFieldForFk, GenTableFieldForPage, GenTableFieldForRule, GenTableIndex } from '@/views/gen/table/model'
  import { usePanel } from '@/components/ext'
  import { EModelCommProps } from '@/components/ext/types'
  import { camelCase, snakeCase, uniqueId } from 'lodash-es'
  import { commonFields } from '@/views/gen/table/commonFields'
  import { IFormData } from 'easy-descriptor'

  const activeTab = defineModel<string>('activeTab', { default: 'db' })

  const tableFields = defineModel<GenTableField[]>('tableFields', { default: [] })
  const tableIndexs = defineModel<GenTableIndex[]>('tableIndexs', { default: [] })

  const handleAddTableField = (formData: IFormData<GenTableFieldForDB>) => {
    tableFields.value.push({
      id: uniqueId(tempIdPrefix),
      ...formData,
      length: 0,
      decimalPlaces: 0,
      allowNull: 1,
      primaryKey: 0
    })
  }

  // 定义通用表格组件的配置属性
  const commonTableProps: EModelCommProps<GenTableFieldForDB>['tableProps'] = {
    // 禁用操作按钮
    actions: false,
    // 隐藏分页功能
    showPage: false,
    // 允许编辑
    enableEdit: true,
    // 禁用自动加载数据
    autoLoad: false,
    // 在显示表单时的回调函数，这里使用 handleAddTableField 函数处理
    // data: tableFields,
    onShowForm: handleAddTableField,
    // 额外的表格属性
    tableProps: {
      // 允许表格行多行显示
      singleLine: false
    },
    auth: false
  }

  /**
   * 处理添加表格索引
   *
   * 此函数用于处理添加表格索引的逻辑它接收一个包含表格索引信息的表单数据对象，
   * 并将其添加到tableIndexs.value数组中，以便在UI上展示新的表格索引
   *
   * @param formData 包含表格索引信息的表单数据对象，类型为IFormData<GenTableIndex>
   */
  const handleAddTableIndex = (formData: IFormData<GenTableIndex>) => {
    console.log('handleAddTableIndex')
    tableIndexs.value.push({
      ...formData,
      id: '1'
    })
  }

  // 定义索引表的属性，这些属性决定了表格如何显示以及与用户交互
  const indexTableProps: EModelCommProps<GenTableFieldForDB>['tableProps'] = {
    // 继承通用的表格属性，这些属性可能包括默认的布局、样式等
    ...commonTableProps,
    // 当用户操作显示表单时，调用handleAddTableIndex方法处理添加索引的逻辑
    onShowForm: handleAddTableIndex
  }

  const tempIdPrefix = 'tmp_'

  const columnNameOptions = computed(() => (rowIndex: number) => {
    const name = tableFields.value[rowIndex].columnName
    return commonFields
      .map(({ columnName }) => ({ label: columnName, value: columnName }))
      .filter(
        ({ value }) =>
          name && value?.toLocaleLowerCase().includes(name.toLocaleLowerCase()) && !tableFields.value.some(({ columnName }) => columnName === value)
      )
  })

  const columnNameChangeHandle = (event: Event, rowIndex: number) => {
    const inputElement = event.target as HTMLInputElement
    const value = inputElement.value
    if (commonFields.some(({ columnName }) => columnName === value)) {
      tableFields.value[rowIndex] = commonFields.find(({ columnName }) => columnName === value)!
    } else {
      tableFields.value[rowIndex].fieldName = camelCase(value)
      tableFields.value[rowIndex].columnName = snakeCase(value)
    }
  }

  let dbTableRef, dbTableProps: ETableProps<GenTableFieldForDB>
  let pageTableRef, pageTableProps: ETableProps<GenTableFieldForPage>
  let ruleTableRef, ruleTableProps: ETableProps<GenTableFieldForRule>
  let fkTableRef, fkTableProps: ETableProps<GenTableFieldForFk>
  let idxTableRef, idxTableProps: ETableProps<GenTableIndex>

  const showTable = ref<boolean>(false)
  onMounted(() => {
    // 延迟显示表格，避免页面渲染时卡顿
    setTimeout(() => {
      const dbOpts = usePanel(GenTableFieldForDB, { tableProps: commonTableProps })
      dbTableRef = dbOpts.refs.tableRef
      dbTableProps = dbOpts.commProps.tableProps
      // 初始化数据库表字段模型
      // const {
      //   refs: { tableRef: dbTableRef },
      //   commProps: { tableProps: dbTableProps }
      // } = usePanel(GenTableFieldForDB, { tableProps: commonTableProps })

      const pageOpts = usePanel(GenTableFieldForPage, { tableProps: commonTableProps })
      pageTableRef = pageOpts.refs.tableRef
      pageTableProps = pageOpts.commProps.tableProps

      // 初始化分页表字段模型
      // const {
      //   refs: { tableRef: pageTableRef },
      //   commProps: { tableProps: pageTableProps }
      // } = usePanel(GenTableFieldForPage, { tableProps: commonTableProps })

      const ruleOpts = usePanel(GenTableFieldForRule, { tableProps: commonTableProps })
      ruleTableRef = ruleOpts.refs.tableRef
      ruleTableProps = ruleOpts.commProps.tableProps

      // 初始化规则表字段模型
      // const {
      //   refs: { tableRef: ruleTableRef },
      //   commProps: { tableProps: ruleTableProps }
      // } = usePanel(GenTableFieldForRule, { tableProps: commonTableProps })

      // 初始化外键表字段模型
      const fkOpts = usePanel(GenTableFieldForFk, { tableProps: commonTableProps })
      fkTableRef = fkOpts.refs.tableRef
      fkTableProps = fkOpts.commProps.tableProps

      // const {
      //   refs: { tableRef: fkTableRef },
      //   commProps: { tableProps: fkTableProps }
      // } = fkOpts

      // 初始化索引表字段模型
      const indexOpts = usePanel(GenTableIndex, { tableProps: indexTableProps })
      idxTableRef = indexOpts.refs.tableRef
      idxTableProps = indexOpts.commProps.tableProps
      // const {
      //   refs: { tableRef: idxTableRef },
      //   commProps: { tableProps: idxTableProps }
      // } = indexOpts
      nextTick(() => {
        setTimeout(() => {
          showTable.value = true
        }, 100)
      })
    }, 100)
  })
</script>

<template>
  <n-tabs v-model:value="activeTab" type="line" animated>
    <n-tab-pane name="db" tab="数据库属性" display-directive="show:lazy">
      <e-table v-if="showTable" ref="dbTableRef" v-bind="dbTableProps" :data="tableFields" data-key="columnName">
        <template ##columnName="row, index">
          <n-auto-complete
            v-model:value="row.columnName"
            :input-props="{ autocomplete: 'disabled' }"
            :options="columnNameOptions(index)"
            clearable
            @change="
              (event: Event) => {
                columnNameChangeHandle(event, index)
              }
            "
          />
        </template>
      </e-table>
    </n-tab-pane>
    <n-tab-pane name="page" tab="页面属性" display-directive="show">
      <e-table v-if="showTable" ref="pageTableRef" v-bind="pageTableProps" :data="tableFields" data-key="columnName" />
    </n-tab-pane>
    <n-tab-pane name="rule" tab="校验字段" display-directive="show">
      <e-table v-if="showTable" ref="ruleTableRef" v-bind="ruleTableProps" :data="tableFields" data-key="columnName" />
    </n-tab-pane>
    <n-tab-pane name="fk" tab="外键" display-directive="show">
      <e-table v-if="showTable" ref="fkTableRef" v-bind="fkTableProps" :data="tableFields" data-key="columnName" />
    </n-tab-pane>
    <n-tab-pane name="idx" tab="索引" display-directive="show">
      <e-table v-if="showTable" ref="idxTableRef" v-bind="idxTableProps" :data="tableIndexs" data-key="columnName" />
    </n-tab-pane>
  </n-tabs>
</template>

<style scoped></style>
